package oldcode;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;

import java.util.Map;

import org.apache.log4j.Logger;

import com.to8to.kitt.ThriftMessage;


@Sharable
public class ClientChannelHandler extends ChannelHandlerAdapter {
	
	public static Logger logger = Logger.getLogger(ClientChannelHandler.class);  
	
	public long ts;
	
	public Map<Integer, Integer> msgs;
	
	public ChannelPool channelPool;
	
	public boolean isdone = false;
	
	public void reset()
	{
		ts = System.currentTimeMillis();
	}
	
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }    
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) 
    {
    	
    	ThriftMessage inMsg = (ThriftMessage)msg;
    	
    	int seqid = inMsg.getSeqid();
    	
    	msgs.remove(seqid);
    	
    	channelPool.removePending(ctx.channel(), seqid);
    	
    	int pending = msgs.size();
    	
    	if(pending % 1000 == 0)
    	{
    		System.out.println("pending: " + pending);
    		System.out.println("time: " + (System.currentTimeMillis() - ts));
    	}
    	
    	if(pending < 100)
    	{
    		System.out.println(msgs.size() + ": " + msgs);
    		System.out.println("time: " + (System.currentTimeMillis() - ts));
    	}
    	
    	if(pending == 0)
    	{
    		long t = System.currentTimeMillis();
    		long delta = t - ts;
    		System.out.println("finish, time: " + delta);
    		isdone = true;
    	}
    	
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

    }
}
